#include "user.h"

std::string caesarCipher(const std::string& text, int shift) {
    std::string result;
    for (char c : text) {
        if (isdigit(c)) {
            result += ((c - '0' + shift + 10) % 10 + '0');
        } else if (isupper(c)) {
            result += ((c - 'A' + shift + 26) % 26 + 'A');
        } else if (islower(c)) {
            result += ((c - 'a' + shift + 26) % 26 + 'a');
        } else {
            result += c;
        }
    }
    return result;
}

std::string AccountManager::encryptPassword(const std::string& password) {
    return caesarCipher(password, caesarShift);
}

std::string AccountManager::decryptPassword(const std::string& encrypted) {
    return caesarCipher(encrypted, -caesarShift);
}

void AccountManager::saveAccount(const std::string& username, const std::string& encryptedPassword) {
    std::ofstream file(dbFile, std::ios::app);
    if (file.is_open()) {
        file << username << " " << encryptedPassword << "\n";
        file.close();
    } else {
        std::cerr << "error" << std::endl;
    }
}

bool AccountManager::findUser(const std::string& username, std::string& outEncryptedPassword) {
    std::ifstream file(dbFile);
    std::string storedUsername, storedPassword;
    
    while (file >> storedUsername >> storedPassword) {
        if (storedUsername == username) {
            outEncryptedPassword = storedPassword;
            return true;
        }
    }
    return false;
}

bool AccountManager::registerUser(std::string username, std::string password) {
    std::string existingPassword;
    if (findUser(username, existingPassword)) {
        std::cout << "exits\n";
        return false;
    }

    std::string encryptedPassword = encryptPassword(password);
    saveAccount(username, encryptedPassword);
    std::cout << "welcome "<<username<<"!\n";
    return true;
}

bool AccountManager::login(std::string username, std::string password) {
    std::string storedEncryptedPassword;
    if (!findUser(username, storedEncryptedPassword)) {
        std::cout << "error\n";
        return false;
    }

    std::string encryptedInput = encryptPassword(password);
    if (encryptedInput == storedEncryptedPassword) {
        std::cout << "welcome " << username << "!\n";
        return true;
    } else {
        std::cout << "error\n";
        return false;
    }
}
